<template>
  <div class="changeCompany layout-content">
    <c-table
      :data="tableData"
      :columns="tableColumns"
      rowKey="companyId"
      :add="
        (user.authState === authDict.finish.value ||
          (user.authState !== authDict.finish.value && tableData.length > 1)) &&
          isActivate
      "
      addText="添加多公司抬头"
      @onAdd="addCompany"
      :loading="loading"
      @onReload="getCompanys"
    >
      <template v-slot:authState="{ row }">
        <AuthStatus :flag="row" />
      </template>
      <template v-slot:handle="{ row }">
        <div class="handle">
          <span>
            <c-button
              type="link"
              v-if="
                row.authenticationStatus === 0 &&
                  user.company &&
                  user.company.id !== row.companyId
              "
              @click="changeCompany(row)"
              >切换到此公司</c-button
            >
            <c-button
              type="link"
              v-if="row.authenticationStatus === 2"
              @click="authenticationAgain(row)"
              >重新认证</c-button
            >
            <c-button
              type="link"
              v-if="
                row.authenticationStatus === 4 &&
                  row.authState !== authDict.backfill.value
              "
              @click="activateCompany(row)"
            >
              激活
            </c-button>
            <c-button
              type="link"
              v-if="row.authState === authDict.backfill.value"
              @click="authenticationContinue(row)"
              >回填金额</c-button
            >
            <a-popconfirm
              v-if="
                user.company &&
                  user.company.id !== row.companyId &&
                  !$isSuperAdmin(row.roleId) &&
                  $btn('delUserCompany') &&
                  [
                    authDict.finish.value,
                    authDict.failed.value,
                    authDict.inactive_company.value,
                    authDict.inactive_personal.value
                  ].indexOf(row.authState) !== -1
              "
              :title="`是否确认删除${row.companyName}？`"
              @confirm="delCompany(row.companyId)"
            >
              <c-button type="link">删除</c-button>
            </a-popconfirm>
            <a-popconfirm
              v-if="
                user.company &&
                  user.company.id !== row.companyId &&
                  $isSuperAdmin(row.roleId) &&
                  row.authState === authDict.failed.value &&
                  $btn('delUserNewCompany') &&
                  [
                    authDict.finish.value,
                    authDict.failed.value,
                    authDict.inactive_company.value,
                    authDict.inactive_personal.value
                  ].indexOf(row.authState) !== -1
              "
              :title="`是否确认删除${row.companyName}？`"
              @confirm="delSuperCompany(row.preAuthId)"
            >
              <c-button type="link">删除</c-button>
            </a-popconfirm>
          </span>
          <span v-if="user.company && user.company.id === row.companyId"
            >当前登录</span
          >
        </div>
      </template>
    </c-table>
    <c-modal
      v-model="changeCompanyVisible"
      title=""
      noFooter
      :closeable="false"
    >
      <div class="changeCompanyModal tc">
        <a-spin /><span style="padding: 0px 5px 0 15px;">正在切换至</span
        ><span class="primary">{{ changeCompanyName }}</span>
      </div>
    </c-modal>
  </div>
</template>

<script>
import {
  selectcompanylist,
  removeusercompanyauth,
  removeusernewcompanyauthfail
} from "@/api/company";
import { selectcompany } from "@/api/auth";
import { companyactivate } from "@/api/activate";
import authDict from "@/dict/auth";
import roleDict from "@/dict/role";
import { mapState, mapActions } from "vuex";
import AuthStatus from "@/components-business/auth/status";

export default {
  components: {
    AuthStatus
  },
  data() {
    return {
      authDict,
      loading: false,
      tableData: [],
      tableColumns: [
        {
          title: "公司名称",
          dataIndex: "companyName"
        },
        {
          title: "员工身份",
          dataIndex: "roleName"
        },
        {
          title: "身份认证状态",
          dataIndex: "authState",
          scopedSlots: { customRender: "authState" }
        },
        {
          title: "操作",
          scopedSlots: { customRender: "handle" }
        }
      ],
      changeCompanyVisible: false,
      changeCompanyName: undefined // 要切换的公司名称
    };
  },
  computed: {
    ...mapState(["user", "socket"]),
    // 是否已激活
    isActivate() {
      let res =
        [
          authDict.inactive_personal.value,
          authDict.inactive_company.value
        ].indexOf(this.user.authState) === -1;
      return res;
    }
  },
  watch: {
    "socket.loginWsReadyState"() {
      // 切换公司时，等待loginWs关闭后，发起静默登录
      if (this.socket.loginWsReadyState === null && this.socket.changeCompany) {
        // 发起静默登录
        this.silentLogin()
          .then(() => {
            // 更新accessToken
            setTimeout(() => {
              this.changeCompanyVisible = false;
            }, 2000);
          })
          .finally(() => {
            // 删除正在切换公司标识
            this.setChangeCompany(false);
            this.getCompanys();
          });
      }
    }
  },
  methods: {
    ...mapActions(["silentLogin", "setChangeCompany"]),
    // 激活企业
    activateCompany(row) {
      // 是否未激活超级管理员
      if (row.roleId === roleDict.unactivatesuper.value) {
        this.$router.push({
          name: "activateCompany",
          query: { id: row.companyId }
        });
      } else {
        companyactivate({
          companyId: row.companyId
        }).then(() => {
          this.$notification.success({
            message: "激活成功",
            description: "恭喜你，企业激活成功"
          });
          this.getCompanys();
        });
      }
    },
    // 重新认证
    authenticationAgain(row) {
      this.$storage.s_set("authenticationContinue", true);
      this.$router.push({
        name: "authentication",
        query: { id: row.companyId, name: row.companyName }
      });
    },
    // 回填金额
    authenticationContinue(row) {
      // this.$storage.s_set("authenticationContinue", true);
      // 是否未激活超级管理员
      if (row.roleId === roleDict.unactivatesuper.value) {
        this.$router.push({
          name: "activateCompany",
          params: { backfill: row.flowId }
        });
      } else {
        this.$storage.s_set("addCompany-backfill", row.flowId);
        this.$router.push({ name: "authentication" });
      }
    },
    // 查询所有公司抬头
    getCompanys() {
      this.loading = true;
      selectcompanylist()
        .then(res => {
          this.tableData = res;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 添加公司抬头
    addCompany() {
      this.$storage.s_set("addCompany", true);
      this.$router.push({ name: "authentication" });
    },
    // 删除公司抬头（超管以外身份）
    delCompany(id) {
      removeusercompanyauth({
        companyId: id
      }).then(() => {
        this.$message.success("操作成功");
        this.getCompanys();
      });
    },
    // 删除公司抬头（身份是超管且认证失败）
    delSuperCompany(id) {
      removeusernewcompanyauthfail({
        preAuthId: id
      }).then(() => {
        this.$message.success("操作成功");
        this.getCompanys();
      });
    },
    // 切换公司抬头
    changeCompany(companyData) {
      this.changeCompanyName = companyData.companyName;
      this.changeCompanyVisible = true;
      selectcompany({
        companyId: companyData.companyId
      })
        .then(res => {
          // 标识正在切换公司
          this.setChangeCompany(true).then(() => {
            // 获取当前登录手机号，拼接成当前账号存储的accessToken名称
            let loginPhone = this.$storage.get("loginPhone");
            let access_token = this.$globalSite.accessToken + loginPhone;
            this.$storage.set(access_token, res.accessToken);
            // 关闭ws
            this.socket.loginWs.close();
            // setTimeout(()=>{
            //   // 发起静默登录
            //   this.silentLogin()
            //     .then(() => {
            //       // 更新accessToken
            //       setTimeout(() => {
            //         this.changeCompanyVisible = false;
            //       }, 2000);
            //     })
            //     .finally(() => {
            //       // 删除正在切换公司标识
            //       this.setChangeCompany(false);
            //       this.getCompanys();
            //     });
            // },2000)
          });
        })
        .catch(() => {
          this.changeCompanyVisible = false;
        });
    }
  },
  created() {
    this.getCompanys();
  }
};
</script>

<style lang="scss" scoped>
.changeCompanyModal {
  font-size: 18px;
}
</style>
